﻿using Microsoft.Web.WebView2.Core;

namespace shbxdv
{
    public partial class EzvizPTZCtrlFullForm : Form
    {
        private string deviceSerial = string.Empty;
        private string deviceCode = string.Empty;
        private string accessToken = string.Empty;
        public EzvizPTZCtrlFullForm()
        {
            InitializeComponent();
        }
        public EzvizPTZCtrlFullForm(string _devSerial, string _deviceCode, string _accessToken)
        {
            InitializeComponent();

            deviceSerial = _devSerial;
            deviceCode = _deviceCode;
            accessToken = _accessToken;
        }

        private void EzvizPTZCtrlFullForm_Load(object sender, EventArgs e)
        {
            int x = this.Width;
            int y = this.Height;
            //将退出按钮图标定位在屏幕的右下角
            this.btnExitFullScreen.Location = new Point(x - 250, y - 150);

            //初始化设置目录
            string filePath = GetDebugFilePath("lib/mapHtml/index.html");
            if (!File.Exists(filePath))
            {
                MessageBox.Show("视频播放模板文件【" + filePath + "】不存在", "工地直播播放提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                this.videoView2.Source = new Uri(@"file:///" + filePath);
                this.UrlCheck();
            }
        }
        /// <summary>
        /// 导航初始化完成进行的操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void videoView2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            // 确保导航到登录页面完成
            if (e.IsSuccess)
            {                // 执行网页JS代码，自动加载直播视频
                string info = $"ezopenInit('{deviceSerial}','{deviceCode}','{accessToken}')"; //我的JS 方法是ezopenInit
                await this.videoView2.CoreWebView2.ExecuteScriptAsync(info);
            }
            else
            {
                await this.videoView2.CoreWebView2.ExecuteScriptAsync($"alert('视频播放失败！！！')");
            }
        }
        /// <summary>
        /// 初始化 coreWebview2完成时发生。在完成时进行一系列设置。
        /// </summary>
        private void videoView2_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
        {
            if (e.IsSuccess)
            {
                this.videoView2.CoreWebView2.Settings.IsScriptEnabled = true;
                this.videoView2.CoreWebView2.Settings.IsStatusBarEnabled = false;
                this.videoView2.CoreWebView2.Settings.AreDevToolsEnabled = false;
                //this.mainView2.CoreWebView2.Settings.AreHostObjectsAllowed = true;
                //禁止所有菜单
                this.videoView2.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;
            }
            else
            {
                // 初始化失败，记录错误或显示消息
                string errorMessage = e.InitializationException?.Message ?? "未知错误";
                // 这里可以添加日志记录代码，例如使用日志库记录错误
                MessageBox.Show($"WebView2 初始化失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 路径验证
        /// </summary>
        public void UrlCheck()
        {
            //对于不合法的导航路径进行提示
            this.videoView2.NavigationStarting += (object sender, CoreWebView2NavigationStartingEventArgs args) =>
            {
                String url = args.Uri;
                String text = "is not safe, try an https link";
                if (!url.StartsWith("https://") && !url.StartsWith(@"file:///"))
                {
                    this.videoView2.ExecuteScriptAsync($"alert('{url} {text}')");
                    args.Cancel = true;
                }
            };
        }

        private void EzvizPTZCtrlFullForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //关闭时销毁播放器
            try
            {
                if (this.videoView2.CoreWebView2 != null)
                {
                    this.videoView2.CoreWebView2.ExecuteScriptAsync("destroy()");
                }
                this.Dispose();
            }
            catch (Exception ex)
            {
                // 处理异常，比如记录日志或显示错误消息
                MessageBox.Show($"执行脚本时出错: {ex.Message}");
            }
        }

        private void videoView2_DoubleClick(object sender, EventArgs e)
        {
            this.Close();
        }

        private void videoView2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Escape || e.KeyChar == (char)Keys.F11)//按下ESC或者F11 //27
            {
                this.Close();
            }
        }

        private void btnExitFullScreen_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        public static string GetDebugFilePath(string relativePath)
        {
            return Path.GetFullPath(Path.Combine(GetStartupPath(), relativePath));
        }
        public static string GetStartupPath()
        {
            //获取可执行目录地址
            //string exePath = Application.ExecutablePath;

            //string path3 = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            //string path4 = System.IO.Directory.GetCurrentDirectory();
            //string path5 = System.Environment.CurrentDirectory;
            //string path6 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            //string path7 = System.AppDomain.CurrentDomain.BaseDirectory;

            return Application.StartupPath;
        }
    }
}
